import React, {Component} from 'react';
import {
    Button, Platform, StyleSheet,
    Text, TextInput, View,
    Dimensions, TouchableOpacity,
    Image, FlatList,
} from 'react-native';
import CS from "../common/CS";
import WidgetUtils from "../common/WidgetUtils";
import NativeUtils from "../common/NativeUtils";
import ToastUtils from "../common/ToastUtils";

const {width: sw, height: sh, scale: ss} = Dimensions.get('window');

export default class AddFile extends React.Component {

    itemData = {};
    sourceAllData = [];
    searchText = '';
    dialogTitle = '';
    dialogContent = '';

    constructor() {
        super();
        this.state = {
            refreshing: false,
            isShowCancelBtn: false,
            isShowSearchOption: false,
            isShowDialog: false,
            isFilterChinese: false,
            inputOptionValue: '',
            sourceData: [],
            itemHeight: sw * 0.12,
            modalVisible: false,

        };

        // for (let i = 0; i < 21; i++) {
        //     this.state.sourceData.push({item: i});
        // }
    }

    componentDidMount() {
        this.readFile();
    }

    readFile() {
        Platform.OS === "ios" ? this._readFileIOS() : this._readFileAndroid();
    }

    static navigationOptions = {
        header: null,
    };

    render() {
        return (
            <View style={{flex: 1, backgroundColor: CS.backgroud}}>
                {WidgetUtils._getStatusBar(true)}
                {this._renderTop()}
                {this._renderSearchOption()}
                {this._renderFlatList()}
                {WidgetUtils._showDialog(this, '提示', '是否添加到书架？', this._dialogSure)}
            </View>
        );
    }

    _dialogSure = (boolen) => {
        if (boolen === true) {
            //读取内容
            // NativeUtils.readFileContent(this.itemData.path, (content) => {
            //     console.log(content);
            // });
            this.props.navigation.state.params.callBack(this.itemData);
            ToastUtils.show('添加成功,返回查看哦!');
        }
    };

    _renderTop() {
        let leftRight = sw * 0.02;
        let itemHeiht = sw * 0.07;
        return <View
            style={{
                backgroundColor: CS.greenLight,
                height: WidgetUtils.headerHeight,
                paddingTop: WidgetUtils.headerPaddingTop,
                flexDirection: 'row',
                alignItems: 'center'
            }}>
            <TouchableOpacity
                activeOpacity={WidgetUtils.activeOpacity}
                onPress={() => {
                    this.props.navigation.goBack()
                }}
                style={{
                    width: itemHeiht,
                    height: itemHeiht,
                    borderRadius: itemHeiht / 2,
                    justifyContent: 'center',
                    marginLeft: leftRight,
                    backgroundColor: CS.green,
                    alignItems: 'center',
                }}>
                <Image
                    source={require('../icon/toright_white.png')}
                    resizeMode={'contain'}
                    style={{width: sw * 0.035, height: sw * 0.035, transform: [{rotateY: '180deg'}]}}
                />
            </TouchableOpacity>
            <View style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                marginLeft: leftRight,
                marginRight: leftRight,
            }}>
                <View style={{
                    backgroundColor: CS.white,
                    borderRadius: sw * 0.035,
                    borderWidth: 1 / ss,
                    borderColor: CS.green,
                    height: itemHeiht,
                    alignItems: 'center',
                    flexDirection: 'row',
                    paddingLeft: 10,
                    paddingRight: 2,
                }}>

                    <Image source={require('../icon/main_search_blank.png')}
                           style={{width: sw * 0.04, height: sw * 0.04}}/>
                    <TextInput
                        ref={ref => this.vTextInput = ref}
                        placeholder={'搜索列表'}
                        placeholderTextColor={CS.gray99}
                        returnKeyType={'done'}  // 跨平台支持的值：done、go、next、search、send
                        underlineColorAndroid='transparent'
                        onChangeText={this._onTextChant}
                        onEndEditing={this._search}
                        style={{
                            flex: 1,
                            fontSize: 14,
                            color: CS.gray99,
                            backgroundColor: CS.tran,
                            height: sw * 0.17,
                            textAlign: 'auto',
                        }}/>
                    <TouchableOpacity
                        ref={ref => this.vCancel = ref}
                        activeOpacity={0.5}
                        onPress={() => {
                            this.vTextInput.clear();
                            this._onTextChant('');
                            this.setState({
                                isShowCancelBtn: false
                            });
                        }}
                        style={{
                            width: sw * 0.07, height: sw * 0.07, justifyContent: 'center',
                            display: this.state.isShowCancelBtn ? 'flex' : 'none',
                            alignItems: 'center',
                        }}>
                        <Image source={require('../icon/main_search_cancel.png')}
                               style={{width: sw * 0.04, height: sw * 0.04,}}/>

                    </TouchableOpacity>
                </View>
            </View>
            <TouchableOpacity
                onPress={this._search}
                activeOpacity={0.5} style={{
                width: sw * 0.12,
                height: itemHeiht,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: CS.green,
                marginRight: leftRight,
                borderRadius: CS.borderRadius,
            }}
            >
                <Text style={{
                    fontSize: 16,
                    color: CS.fontColor,
                }}>搜索</Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={() => {
                    this.setState({isShowSearchOption: !this.state.isShowSearchOption})
                    this.state.inputOptionValue = '';
                    this.state.isFilterChinese = false;
                    this._search();
                }}
                style={{
                    width: sw * 0.07,
                    height: sw * 0.07,
                    borderRadius: sw * 0.35,
                    backgroundColor: CS.greenDark,
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginLeft: 3,
                    marginRight: leftRight,
                    display: 'flex',
                    flexDirection: 'row',
                }}>
                <Image source={require('../icon/main_set.png')}
                       style={{width: sw * 0.045, height: sw * 0.045,}}/>
            </TouchableOpacity>
        </View>;
    }

    _search = () => {
        let temp = [];
        if (this.searchText.length > 0) {
            for (let i = 0; i < this.sourceAllData.length; i++) {
                if (this.sourceAllData[i].title.indexOf(this.searchText) != -1) {
                    temp.push(this.sourceAllData[i]);
                }
            }
        } else {
            temp = this.sourceAllData;
        }

        let temp2 = [];
        if (this.state.isFilterChinese) {
            for (let i = 0; i < temp.length; i++) {
                let obj = temp[i];
                if (WidgetUtils._isContainChinese(obj.title)) {
                    temp2.push(obj);
                }
            }
        } else {
            temp2 = temp;
        }

        let temp3 = [];
        let value = parseInt(this.state.inputOptionValue);
        if (value > 0) {
            for (let i = 0; i < temp2.length; i++) {
                let obj = temp2[i];
                if ((obj.size / 1024) >= value) {
                    temp3.push(obj);
                }
            }
        } else {
            temp3 = temp2;
        }

        this.setState({
            sourceData: temp3,
        });
    };

    _readFileIOS = () => {
        alert('IOS');
    };

    _readFileAndroid = () => {
        this.setState({
            refreshing: true,
        });
        this.sourceAllData
        NativeUtils.readNovelFile((string) => {
            let sourceAllData = JSON.parse(string);
            console.log(sourceAllData);
            this.sourceAllData = sourceAllData;
            this.setState({
                refreshing: false,
            });
            this._search();
        });
    };

    _keyExtractor = (item, index) => index + '';

    _itemOnPress = (item) => {
        this.itemData = item;
        this.setState({
            isShowDialog: true,
        })
    };
    _renderItem = ({item}) => {
        let image;
        if (item.path.endsWith('.txt')) {
            image = require('../icon/file_type_txt.png');
        } else if (item.path.endsWith('.umd')) {
            image = require('../icon/file_type_umd.png');
        } else if (item.path.endsWith('.epub')) {
            image = require('../icon/file_type_epub.png');
        } else {
            image = require('../icon/file_type_txt.png');
        }
        return (
            <TouchableOpacity
                onPress={() => this._itemOnPress(item)}
                activeOpacity={WidgetUtils.activeOpacity}
                style={{height: sw * 0.12, alignItems: 'center', flexDirection: 'row'}}>
                <Image source={image}
                       resizeMode={'contain'}
                       style={{width: sw * 0.10, height: sw * 0.10}}/>
                <View style={{justifyContent: 'center', marginLeft: sw * 0.02}}>
                    <Text
                        numberOfLines={1}
                        ellipsizeMode={'middle'}
                        style={{
                            fontSize: sw * 0.035,
                            width: sw * 0.85
                        }}>{item.title}</Text>
                    <View style={{flexDirection: 'row', marginTop: sw * 0.000}}>
                        <Text style={{fontSize: sw * 0.030}}></Text>
                        <Text style={{
                            fontSize: sw * 0.030,
                            color: CS.green,
                            marginLeft: 5
                        }}>{WidgetUtils._getSize(item.size)}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    _renderFlatList() {
        return <FlatList
            ref={ref => this.vFlatList = ref}
            data={this.state.sourceData}
            showsVerticalScrollIndicator={false}
            // extraData={this.state.selected}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
            //初始加载的条数，不会被卸载
            // initialNumToRender={15}
            //分割线
            ItemSeparatorComponent={this._renderItemSeparatorComponent}
            ListEmptyComponent={WidgetUtils._renderEmptyView()}
            onLayout={this._setItemHeight} //设置item高度

            refreshing={this.state.refreshing}
            onRefresh={this._renderRefresh}

            // numColumns={1} //宫格布局
            // columnWrapperStyle={{}}
            // horizontal={true}
            style={{flex: 1, marginLeft: sw * 0.03, marginRight: sw * 0.03,}}
        />;
    }

    //分割线
    _renderItemSeparatorComponent = ({highlighted}) => {
        return (
            <View style={{height: 1, backgroundColor: CS.greenLight}}></View>
        )
    };

    //下拉刷新
    _renderRefresh = () => {//开始刷新
        this.readFile();
    };

    //设置item高度
    _setItemHeight = (e) => {
        let height = e.nativeEvent.layout.height;
        if (this.state.itemHeight < height) {
            this.setState({itemHeight: height})
        }
    };


    _onTextChant = (text) => {
        this.searchText = text;
        if (text.length > 0) {
            this.setState({
                isShowCancelBtn: true
            });
        } else {
            this._search();
            this.setState({
                isShowCancelBtn: false
            });
        }
    };

    _renderSearchOption() {
        return <View style={{
            width: sw,
            height: sw * 0.1,
            backgroundColor: CS.greenLight,
            display: this.state.isShowSearchOption ? 'flex' : 'none',
        }}>
            <View style={{width: sw, height: 1 / ss, backgroundColor: CS.backgroud}}/>
            <View style={{
                flexDirection: 'row', alignItems: 'center', width: sw,
                height: sw * 0.09,
            }}>
                <Text style={{fontSize: sw * 0.03, marginLeft: sw * 0.10}}>过滤</Text>
                <View style={{
                    width: sw * 0.15,
                    height: sw * 0.06,
                    flexDirection: 'row',
                    alignItems: 'center',
                    borderRadius: 5
                }}>
                    <TextInput
                        placeholder={'10'}
                        placeholderTextColor={CS.gray99}
                        // returnKeyType={'done'}  // 跨平台支持的值：done、go、next、search、send
                        onChangeText={this._onSearchOptionTextChant}
                        onEndEditing={this._onSearchEndEditing}
                        // onKeyPress={}
                        // defaultValue={this.optionSize}
                        maxLength={7}
                        autoFocus={false}
                        keyboardType={'numeric'}
                        value={this.state.inputOptionValue}
                        numberOfLines={1}
                        underlineColorAndroid={CS.tran}
                        style={{
                            backgroundColor: CS.white,
                            marginLeft: 5,
                            height: sw * 0.3,
                            width: sw * 0.15,
                            fontSize: sw * 0.030,
                            padding: 0,
                            color: CS.gray33,
                        }}/>
                </View>
                <Text style={{fontSize: sw * 0.03, marginLeft: sw * 0.01}}>KB以下</Text>
                <TouchableOpacity
                    activeOpacity={CS.activeOpacity}
                    style={{marginLeft: 20, flexDirection: 'row'}}
                    onPress={this._searchOptionFilterPress}
                >
                    <View style={{width: sw * 0.04, height: sw * 0.04, backgroundColor: CS.white}}>
                        <Image source={require('../icon/filter_yes.png')}
                               resizeMode={'contain'}
                               style={{
                                   width: sw * 0.04,
                                   height: sw * 0.04,
                                   display: this.state.isFilterChinese ? 'flex' : 'none'
                               }}/>
                    </View>
                    <Text style={{fontSize: sw * 0.03, marginLeft: sw * 0.01}}>过滤不包含中文名</Text>
                </TouchableOpacity>
            </View>
        </View>
    }

    _searchOptionFilterPress = () => {
        this.state.isFilterChinese = !this.state.isFilterChinese;
        let is = this.state.isFilterChinese;
        this.setState({
            isFilterChinese: is,
        });
        this._search();
    };

    _onSearchEndEditing = (text) => {
        this._search();
    };

    _onSearchOptionTextChant = (text) => {
        let newText = text.replace(/[^\d]+/, '');
        this.state.inputOptionValue = newText;
        this.setState({inputOptionValue: newText});
        let value = parseInt(this.state.inputOptionValue);
    }
}

const styles = StyleSheet.create({});




